//
//  ImageCache.m
//  FrameTest
//
//  Created by Tiger on 11-11-1.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageCache.h"
#import <commoncrypto/CommonDigest.h>
#define FOLDER_PATH [NSString stringWithFormat:@"%@/Documents/CachedImages",NSHomeDirectory()]

@implementation ImageCache

- (void)dealloc {
    [super dealloc];
}

+ (NSString *)md5:(NSString *)str { 
    const char *cStr = [str UTF8String];
	unsigned char result[16];
	CC_MD5( cStr, strlen(cStr), result );
	return [NSString stringWithFormat:
			@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3], 
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15]
			];
}

+ (void)deleteAllImages
{
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:FOLDER_PATH]){
		[fileManager removeItemAtPath:FOLDER_PATH error:nil];
	}
}

+ (NSString *)cachedSizeString
{
	return nil;
}

+ (BOOL)cacheImageData:(NSData *)imageData strUrl:(NSString *)strUrl {
	if (imageData && strUrl) {
		NSString *fileName = [self md5:strUrl];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		
		if (![fileManager fileExistsAtPath:FOLDER_PATH]){
			[fileManager createDirectoryAtPath:FOLDER_PATH withIntermediateDirectories:YES attributes:nil error:nil];
		}
		
		return [imageData writeToFile:[NSString stringWithFormat:@"%@/%@",FOLDER_PATH,fileName] atomically:YES];

	}
	else {
		return NO;
	}
}

+ (BOOL)cacheImage:(UIImage *)image strUrl:(NSString *)strUrl {
	if (image && strUrl) {
		NSString *fileName = [self md5:strUrl];
		NSData *imageData = UIImagePNGRepresentation(image);
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		
		if (![fileManager fileExistsAtPath:FOLDER_PATH]){
			[fileManager createDirectoryAtPath:FOLDER_PATH withIntermediateDirectories:YES attributes:nil error:nil];
		}
		
		return [imageData writeToFile:[NSString stringWithFormat:@"%@/%@",FOLDER_PATH,fileName] atomically:YES];
		
	}
	else {
		return NO;
	}
}

+ (BOOL)deleteImageWithUrl:(NSString *)strUrl {
	if (strUrl) {
		NSString *fileName = [self md5:strUrl];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSString *path = [NSString stringWithFormat:@"%@/%@",FOLDER_PATH,fileName];
		return [fileManager removeItemAtPath:path error:nil];
	}
	else {
		return NO;
	}
}

+ (UIImage *)selectImageWithUrl:(NSString *)strUrl {
	if (strUrl) {
		NSString *fileName = [self md5:strUrl];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSString *path = [NSString stringWithFormat:@"%@/%@",FOLDER_PATH,fileName];
		
		if ([fileManager fileExistsAtPath:path]) {
			NSData *data = [NSData dataWithContentsOfFile:path];
			UIImage *image = [[UIImage alloc]initWithData:data];
			return [image autorelease];
		}
		else {
			return nil;
		}
	}
	else {
		return nil;
	}
}

@end
